<template>
  <div class="financial-records-container">
    <!-- 筛选区域 -->
    <el-card shadow="never" class="filter-card">
      <el-form :inline="true" :model="filterForm">
        <el-form-item label="交易类型">
          <el-select v-model="filterForm.transactionType" placeholder="全部" clearable>
            <el-option label="租金" value="rent"></el-option>
            <el-option label="押金" value="deposit"></el-option>
            <el-option label="佣金" value="commission"></el-option>
            <el-option label="违约金" value="penalty"></el-option>
            <el-option label="其他" value="other"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="日期范围">
          <el-date-picker
              v-model="filterForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="支付方式">
          <el-select v-model="filterForm.paymentMethod" placeholder="全部" clearable>
            <el-option label="现金" value="cash"></el-option>
            <el-option label="银行转账" value="bank"></el-option>
            <el-option label="微信支付" value="wechat"></el-option>
            <el-option label="支付宝" value="alipay"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <div class="operation-buttons">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon> 新增记录
      </el-button>
    </div>

    <!-- 收支记录表格 -->
    <el-card shadow="never" class="table-card">
      <el-table
          :data="filteredTableData"
          border
          stripe
          style="width: 100%"
          v-loading="loading"
      >
        <el-table-column prop="transactionId" label="交易ID" width="100" />
        <el-table-column prop="transactionDate" label="交易日期" width="120" />
        <el-table-column label="交易类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getTransactionTypeTag(row.transactionType)">
              {{ formatTransactionType(row.transactionType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="金额" width="120" align="right">
          <template #default="{ row }">
            {{ formatCurrency(row.amount) }}
          </template>
        </el-table-column>
        <el-table-column prop="paymentMethod" label="支付方式" width="120">
          <template #default="{ row }">
            {{ formatPaymentMethod(row.paymentMethod) }}
          </template>
        </el-table-column>
        <el-table-column prop="relatedHouse" label="关联房源" width="180" />
        <el-table-column prop="relatedClient" label="关联客户" width="150" />
        <el-table-column prop="operator" label="操作人" width="120" />
        <el-table-column prop="remark" label="备注" show-overflow-tooltip />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row.transactionId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :total="pagination.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="600px"
        :close-on-click-modal="false"
    >
      <el-form
          ref="recordFormRef"
          :model="recordForm"
          :rules="rules"
          label-width="100px"
      >
        <el-form-item label="交易类型" prop="transactionType">
          <el-select
              v-model="recordForm.transactionType"
              placeholder="请选择交易类型"
              style="width: 100%"
          >
            <el-option label="租金" value="rent"></el-option>
            <el-option label="押金" value="deposit"></el-option>
            <el-option label="佣金" value="commission"></el-option>
            <el-option label="违约金" value="penalty"></el-option>
            <el-option label="其他" value="other"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="金额" prop="amount">
          <el-input-number
              v-model="recordForm.amount"
              :precision="2"
              :min="0"
              :controls="false"
              style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="支付方式" prop="paymentMethod">
          <el-select
              v-model="recordForm.paymentMethod"
              placeholder="请选择支付方式"
              style="width: 100%"
          >
            <el-option label="现金" value="cash"></el-option>
            <el-option label="银行转账" value="bank"></el-option>
            <el-option label="微信支付" value="wechat"></el-option>
            <el-option label="支付宝" value="alipay"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="交易日期" prop="transactionDate">
          <el-date-picker
              v-model="recordForm.transactionDate"
              type="date"
              placeholder="选择日期"
              value-format="YYYY-MM-DD"
              style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="关联房源">
          <el-select
              v-model="recordForm.relatedHouseId"
              filterable
              remote
              reserve-keyword
              placeholder="请输入房源关键词"
              :remote-method="searchHouses"
              :loading="houseLoading"
              style="width: 100%"
          >
            <el-option
                v-for="item in houseOptions"
                :key="item.houseId"
                :label="`${item.houseName} (${item.houseCode})`"
                :value="item.houseId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="关联客户">
          <el-select
              v-model="recordForm.relatedClientId"
              filterable
              remote
              reserve-keyword
              placeholder="请输入客户姓名或电话"
              :remote-method="searchClients"
              :loading="clientLoading"
              style="width: 100%"
          >
            <el-option
                v-for="item in clientOptions"
                :key="item.clientId"
                :label="`${item.clientName} (${item.phone})`"
                :value="item.clientId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
              v-model="recordForm.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

// 表格数据
const tableData = ref([
  {
    transactionId: 'TR20230001',
    transactionDate: '2023-05-10',
    transactionType: 'rent',
    amount: 3500.00,
    paymentMethod: 'wechat',
    relatedHouse: '阳光花园 3栋502室',
    relatedClient: '张三 (138****1234)',
    operator: '李经理',
    remark: '5月份租金',
    relatedHouseId: '1',
    relatedClientId: '1'
  },
  {
    transactionId: 'TR20230002',
    transactionDate: '2023-05-15',
    transactionType: 'commission',
    amount: 7000.00,
    paymentMethod: 'bank',
    relatedHouse: '城市花园 2栋301室',
    relatedClient: '王五 (139****5678)',
    operator: '张经理',
    remark: '买卖佣金',
    relatedHouseId: '2',
    relatedClientId: '2'
  },
  {
    transactionId: 'TR20230003',
    transactionDate: '2023-05-18',
    transactionType: 'deposit',
    amount: 5000.00,
    paymentMethod: 'alipay',
    relatedHouse: '阳光花园 1栋201室',
    relatedClient: '李四 (137****8910)',
    operator: '王经理',
    remark: '租房押金',
    relatedHouseId: '3',
    relatedClientId: '3'
  },
  {
    transactionId: 'TR20230004',
    transactionDate: '2023-05-20',
    transactionType: 'penalty',
    amount: 1000.00,
    paymentMethod: 'cash',
    relatedHouse: '城市花园 3栋102室',
    relatedClient: '赵六 (136****3456)',
    operator: '李经理',
    remark: '提前解约违约金',
    relatedHouseId: '4',
    relatedClientId: '4'
  },
  {
    transactionId: 'TR20230005',
    transactionDate: '2023-05-22',
    transactionType: 'other',
    amount: 800.00,
    paymentMethod: 'wechat',
    relatedHouse: '阳光花园 2栋302室',
    relatedClient: '钱七 (135****7890)',
    operator: '张经理',
    remark: '物业费代收',
    relatedHouseId: '5',
    relatedClientId: '5'
  },
  {
    transactionId: 'TR20230006',
    transactionDate: '2023-05-25',
    transactionType: 'rent',
    amount: 2800.00,
    paymentMethod: 'bank',
    relatedHouse: '城市花园 1栋501室',
    relatedClient: '孙八 (134****1234)',
    operator: '王经理',
    remark: '5月份租金',
    relatedHouseId: '6',
    relatedClientId: '6'
  },
  {
    transactionId: 'TR20230007',
    transactionDate: '2023-05-28',
    transactionType: 'deposit',
    amount: 3000.00,
    paymentMethod: 'alipay',
    relatedHouse: '阳光花园 4栋101室',
    relatedClient: '周九 (133****5678)',
    operator: '李经理',
    remark: '租房押金',
    relatedHouseId: '7',
    relatedClientId: '7'
  }
])

// 筛选表单
const filterForm = reactive({
  transactionType: '',
  dateRange: [],
  paymentMethod: ''
})

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 加载状态
const loading = ref(false)

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const recordFormRef = ref(null) // 表单引用
const recordForm = reactive({
  transactionId: '',
  transactionType: '',
  amount: 0,
  paymentMethod: '',
  transactionDate: '',
  relatedHouseId: '',
  relatedClientId: '',
  remark: ''
})

// 表单验证规则
const rules = reactive({
  transactionType: [
    { required: true, message: '请选择交易类型', trigger: 'change' }
  ],
  amount: [
    { required: true, message: '请输入金额', trigger: 'blur' },
    { type: 'number', min: 0, message: '金额必须大于0', trigger: 'blur' }
  ],
  paymentMethod: [
    { required: true, message: '请选择支付方式', trigger: 'change' }
  ],
  transactionDate: [
    { required: true, message: '请选择交易日期', trigger: 'change' }
  ]
})

// 房源搜索相关
const houseOptions = ref([])
const houseLoading = ref(false)

// 客户搜索相关
const clientOptions = ref([])
const clientLoading = ref(false)

// 计算属性：过滤后的表格数据
const filteredTableData = computed(() => {
  let result = [...tableData.value]

  // 按交易类型筛选
  if (filterForm.transactionType) {
    result = result.filter(item => item.transactionType === filterForm.transactionType)
  }

  // 按支付方式筛选
  if (filterForm.paymentMethod) {
    result = result.filter(item => item.paymentMethod === filterForm.paymentMethod)
  }

  // 按日期范围筛选
  if (filterForm.dateRange && filterForm.dateRange.length === 2) {
    const [startDate, endDate] = filterForm.dateRange
    result = result.filter(item => {
      const itemDate = new Date(item.transactionDate)
      const start = new Date(startDate)
      const end = new Date(endDate)
      return itemDate >= start && itemDate <= end
    })
  }

  // 更新分页总数
  pagination.total = result.length

  // 分页处理
  const start = (pagination.currentPage - 1) * pagination.pageSize
  const end = start + pagination.pageSize
  return result.slice(start, end)
})

// 初始化数据
onMounted(() => {
  fetchData()
})

// 获取表格数据
const fetchData = () => {
  loading.value = true
  // 模拟API调用
  setTimeout(() => {
    pagination.total = tableData.value.length
    loading.value = false
  }, 500)
}

// 分页大小变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
}

// 当前页变化
const handleCurrentChange = (val) => {
  pagination.currentPage = val
}

// 新增记录
const handleAdd = () => {
  dialogTitle.value = '新增收支记录'
  resetForm()
  dialogVisible.value = true
}

// 编辑记录
const handleEdit = (row) => {
  dialogTitle.value = '编辑收支记录'
  Object.assign(recordForm, {
    transactionId: row.transactionId,
    transactionType: row.transactionType,
    amount: row.amount,
    paymentMethod: row.paymentMethod,
    transactionDate: row.transactionDate,
    relatedHouseId: row.relatedHouseId || '',
    relatedClientId: row.relatedClientId || '',
    remark: row.remark
  })

  // 设置关联房源和客户的选项
  if (row.relatedHouseId) {
    houseOptions.value = [{
      houseId: row.relatedHouseId,
      houseName: row.relatedHouse.split(' ')[0],
      houseCode: row.relatedHouse.match(/\(([^)]+)\)/)?.[1] || ''
    }]
  }

  if (row.relatedClientId) {
    clientOptions.value = [{
      clientId: row.relatedClientId,
      clientName: row.relatedClient.split(' ')[0],
      phone: row.relatedClient.match(/\(([^)]+)\)/)?.[1] || ''
    }]
  }

  dialogVisible.value = true
}

// 删除记录
const handleDelete = (id) => {
  ElMessageBox.confirm('确定要删除这条记录吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    tableData.value = tableData.value.filter(item => item.transactionId !== id)
    ElMessage.success('删除成功')
  }).catch(() => {
    // 取消删除
  })
}

// 提交表单
const submitForm = () => {
  recordFormRef.value?.validate((valid) => {
    if (valid) {
      if (dialogTitle.value === '新增收支记录') {
        // 新增记录
        const newRecord = {
          transactionId: `TR${new Date().getTime()}`,
          transactionType: recordForm.transactionType,
          amount: recordForm.amount,
          paymentMethod: recordForm.paymentMethod,
          transactionDate: recordForm.transactionDate,
          relatedHouse: houseOptions.value.find(h => h.houseId === recordForm.relatedHouseId)?.houseName || '未知房源',
          relatedClient: clientOptions.value.find(c => c.clientId === recordForm.relatedClientId)?.clientName || '未知客户',
          operator: '当前用户',
          remark: recordForm.remark,
          relatedHouseId: recordForm.relatedHouseId,
          relatedClientId: recordForm.relatedClientId
        }
        tableData.value.unshift(newRecord)
        ElMessage.success('新增成功')
      } else {
        // 编辑记录
        const index = tableData.value.findIndex(item => item.transactionId === recordForm.transactionId)
        if (index !== -1) {
          tableData.value[index] = {
            ...tableData.value[index],
            transactionType: recordForm.transactionType,
            amount: recordForm.amount,
            paymentMethod: recordForm.paymentMethod,
            transactionDate: recordForm.transactionDate,
            relatedHouse: houseOptions.value.find(h => h.houseId === recordForm.relatedHouseId)?.houseName || tableData.value[index].relatedHouse,
            relatedClient: clientOptions.value.find(c => c.clientId === recordForm.relatedClientId)?.clientName || tableData.value[index].relatedClient,
            remark: recordForm.remark,
            relatedHouseId: recordForm.relatedHouseId,
            relatedClientId: recordForm.relatedClientId
          }
          ElMessage.success('更新成功')
        }
      }
      dialogVisible.value = false
    }
  })
}

// 重置表单
const resetForm = () => {
  recordForm.transactionId = ''
  recordForm.transactionType = ''
  recordForm.amount = 0
  recordForm.paymentMethod = ''
  recordForm.transactionDate = ''
  recordForm.relatedHouseId = ''
  recordForm.relatedClientId = ''
  recordForm.remark = ''
  houseOptions.value = []
  clientOptions.value = []
}

// 搜索房源
const searchHouses = (query) => {
  if (query) {
    houseLoading.value = true
    // 模拟API调用
    setTimeout(() => {
      houseOptions.value = [
        { houseId: '1', houseName: '阳光花园 3栋502室', houseCode: 'YG-3-502' },
        { houseId: '2', houseName: '城市花园 2栋301室', houseCode: 'CS-2-301' },
        { houseId: '3', houseName: '阳光花园 1栋201室', houseCode: 'YG-1-201' },
        { houseId: '4', houseName: '城市花园 3栋102室', houseCode: 'CS-3-102' },
        { houseId: '5', houseName: '阳光花园 2栋302室', houseCode: 'YG-2-302' },
        { houseId: '6', houseName: '城市花园 1栋501室', houseCode: 'CS-1-501' },
        { houseId: '7', houseName: '阳光花园 4栋101室', houseCode: 'YG-4-101' }
      ].filter(item =>
          item.houseName.includes(query) || item.houseCode.includes(query)
      )
      houseLoading.value = false
    }, 500)
  } else {
    houseOptions.value = []
  }
}

// 搜索客户
const searchClients = (query) => {
  if (query) {
    clientLoading.value = true
    // 模拟API调用
    setTimeout(() => {
      clientOptions.value = [
        { clientId: '1', clientName: '张三', phone: '13800123456' },
        { clientId: '2', clientName: '王五', phone: '13900567890' },
        { clientId: '3', clientName: '李四', phone: '13700891011' },
        { clientId: '4', clientName: '赵六', phone: '13600345678' },
        { clientId: '5', clientName: '钱七', phone: '13500789012' },
        { clientId: '6', clientName: '孙八', phone: '13400123456' },
        { clientId: '7', clientName: '周九', phone: '13300567890' }
      ].filter(item =>
          item.clientName.includes(query) || item.phone.includes(query)
      )
      clientLoading.value = false
    }, 500)
  } else {
    clientOptions.value = []
  }
}

// 格式化交易类型
const formatTransactionType = (type) => {
  const map = {
    rent: '租金',
    deposit: '押金',
    commission: '佣金',
    penalty: '违约金',
    other: '其他'
  }
  return map[type] || type
}

// 格式化支付方式
const formatPaymentMethod = (method) => {
  const map = {
    cash: '现金',
    bank: '银行转账',
    wechat: '微信支付',
    alipay: '支付宝'
  }
  return map[method] || method
}

// 格式化金额
const formatCurrency = (amount) => {
  return '¥' + amount.toFixed(2)
}

// 获取交易类型标签样式
const getTransactionTypeTag = (type) => {
  const map = {
    rent: '',
    deposit: 'success',
    commission: 'warning',
    penalty: 'danger',
    other: 'info'
  }
  return map[type] || ''
}
</script>

<style scoped>
.financial-records-container {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.operation-buttons {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-select, .el-date-picker {
  width: 100%;
}
</style>